package cn.pluss.baselibrary.http;

import android.arch.lifecycle.LifecycleOwner;
import android.text.TextUtils;

import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import com.alibaba.fastjson.parser.Feature;
import com.orhanobut.logger.Logger;
import com.uber.autodispose.AutoDispose;
import com.uber.autodispose.AutoDisposeConverter;
import com.uber.autodispose.android.lifecycle.AndroidLifecycleScopeProvider;

import java.util.ArrayList;

import cn.pluss.baselibrary.http.exception.ServerException;
import cn.pluss.baselibrary.model.net.ResMessageBean;
import cn.pluss.baselibrary.model.net.ResultBean;
import cn.pluss.baselibrary.model.net.ResultPageListBean;
import io.reactivex.Observable;
import io.reactivex.ObservableSource;
import io.reactivex.ObservableTransformer;
import io.reactivex.Single;
import io.reactivex.SingleSource;
import io.reactivex.SingleTransformer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.functions.Function;
import io.reactivex.schedulers.Schedulers;
import okhttp3.ResponseBody;

public class RxUtils {

    public static <T> ObservableTransformer<ResponseBody, ArrayList<T>> rxTranslate2List(final Class<T> tClass) {
        return new ObservableTransformer<ResponseBody, ArrayList<T>>() {
            @Override
            public ObservableSource<ArrayList<T>> apply(Observable<ResponseBody> upstream) {
                return upstream.map(new Function<ResponseBody, ArrayList<T>>() {
                    @Override
                    public ArrayList<T> apply(ResponseBody responseBody) throws Exception {
                        ResMessageBean resMessageBean = JSONObject.parseObject(responseBody.string(), ResMessageBean.class, Feature.InitStringFieldAsEmpty);
                        ResultBean resultBean = JSONObject.parseObject(resMessageBean.getSvcContBean().getResult(), ResultBean.class, Feature.InitStringFieldAsEmpty);
                        Logger.json(JSONObject.toJSONString(resMessageBean.getTcpContBean()));
                        Logger.json(resultBean.getResultData());
                        if ("SUCCESS".equals(resultBean.getResultCode())) {
                            return new ArrayList<>(JSONObject.parseArray(resultBean.getResultData(), tClass));
                        } else {
                            throw new ServerException(resultBean.getResultCode(), resultBean.getResultMsg());
                        }
                    }
                });

            }
        };
    }

    public static <T> ObservableTransformer<ResponseBody, T> rxTranslate2Bean(final Class<T> clazz) {
        return new ObservableTransformer<ResponseBody, T>() {
            @Override
            public ObservableSource<T> apply(Observable<ResponseBody> upstream) {
                return upstream.map(new Function<ResponseBody, T>() {
                    @Override
                    public T apply(ResponseBody responseBody) throws Exception {
                        ResMessageBean resMessageBean = JSONObject.parseObject(responseBody.string(), ResMessageBean.class, Feature.InitStringFieldAsEmpty);
                        ResultBean resultBean = JSONObject.parseObject(resMessageBean.getSvcContBean().getResult(), ResultBean.class, Feature.InitStringFieldAsEmpty);
                        Logger.json(JSONObject.toJSONString(resMessageBean.getTcpContBean()));
                        Logger.json(resultBean.getResultData());
                        if ("SUCCESS".equals(resultBean.getResultCode())) {
                            String resultData = resultBean.getResultData();
                            if (TextUtils.isEmpty(resultData))
                                return JSONObject.parseObject("{}", clazz, Feature.InitStringFieldAsEmpty);
                            return JSONObject.parseObject(resultData, clazz, Feature.InitStringFieldAsEmpty);
                        } else {
                            throw new ServerException(resultBean.getResultCode(), resultBean.getResultMsg());
                        }
                    }
                });
            }
        };
    }

    public static <T> SingleTransformer<ResponseBody, T> rxTranslate2BeanSingle(final Class<T> clazz) {
        return new SingleTransformer<ResponseBody, T>() {
            @Override
            public SingleSource<T> apply(Single<ResponseBody> upstream) {
                return upstream.map(new Function<ResponseBody, T>() {
                    @Override
                    public T apply(ResponseBody responseBody) throws Exception {
                        ResMessageBean resMessageBean = JSONObject.parseObject(responseBody.string(), ResMessageBean.class, Feature.InitStringFieldAsEmpty);
                        ResultBean resultBean = JSONObject.parseObject(resMessageBean.getSvcContBean().getResult(), ResultBean.class, Feature.InitStringFieldAsEmpty);
                        Logger.json(JSONObject.toJSONString(resMessageBean.getTcpContBean()));
                        Logger.json(resultBean.getResultData());
                        if ("SUCCESS".equals(resultBean.getResultCode())) {
                            return JSONObject.parseObject(resultBean.getResultData(), clazz, Feature.InitStringFieldAsEmpty);
                        } else {
                            throw new ServerException(resultBean.getResultCode(), resultBean.getResultMsg());
                        }
                    }
                });
            }
        };
    }

    public static <T> ObservableTransformer<ResponseBody, ResultPageListBean<T>> rxTranslate2PageBean(final Class<T> tClass) {
        return new ObservableTransformer<ResponseBody, ResultPageListBean<T>>() {
            @Override
            public ObservableSource<ResultPageListBean<T>> apply(Observable<ResponseBody> upstream) {
                return upstream.map(new Function<ResponseBody, ResultPageListBean<T>>() {
                    @Override
                    public ResultPageListBean<T> apply(ResponseBody responseBody) throws Exception {
                        ResMessageBean resMessageBean = JSONObject.parseObject(responseBody.string(), ResMessageBean.class, Feature.InitStringFieldAsEmpty);
                        ResultBean resultBean = JSONObject.parseObject(resMessageBean.getSvcContBean().getResult(), ResultBean.class);
                        if ("SUCCESS".equals(resultBean.getResultCode())) {
                            ResultPageListBean<T> resultPageListBean = JSONObject.parseObject(resultBean.getResultData(), new TypeReference<ResultPageListBean<T>>() {
                            });
                            Logger.json(resultBean.getResultData());
                            if (resultPageListBean != null) {
                                resultPageListBean.setList(new ArrayList<>(JSONObject.parseArray(resultPageListBean.getData(), tClass)));
                            } else {
                                resultPageListBean = new ResultPageListBean<T>();
                                resultPageListBean.setList(new ArrayList<T>());
                            }
                            return resultPageListBean;
                        } else {
                            throw new ServerException(resultBean.getResultCode(), resultBean.getResultMsg());
                        }
                    }
                });
            }
        };
    }

    public static ObservableTransformer<ResponseBody, String> rxTranslate2Msg() {
        return new ObservableTransformer<ResponseBody, String>() {
            @Override
            public ObservableSource<String> apply(Observable<ResponseBody> upstream) {
                return upstream.map(new Function<ResponseBody, String>() {
                    @Override
                    public String apply(ResponseBody responseBody) throws Exception {
                        ResMessageBean resMessageBean = JSONObject.parseObject(responseBody.string(), ResMessageBean.class);
                        ResultBean resultBean = JSONObject.parseObject(resMessageBean.getSvcContBean().getResult(), ResultBean.class);
                        Logger.json(JSONObject.toJSONString(resMessageBean.getTcpContBean()));
                        Logger.json(JSONObject.toJSONString(resultBean));
                        if ("SUCCESS".equals(resultBean.getResultCode())) {
                            if (resultBean.getResultMsg() == null) {
                                return "";
                            } else {
                                return resultBean.getResultMsg();
                            }
                        } else {
                            throw new ServerException(resultBean.getResultCode(), resultBean.getResultMsg());
                        }
                    }
                });
            }
        };
    }

    public static SingleTransformer<ResponseBody, String> rxTranslate2MsgSingle() {
        return new SingleTransformer<ResponseBody, String>() {
            @Override
            public SingleSource<String> apply(Single<ResponseBody> upstream) {
                return upstream.map(new Function<ResponseBody, String>() {
                    @Override
                    public String apply(ResponseBody responseBody) throws Exception {
                        ResMessageBean resMessageBean = JSONObject.parseObject(responseBody.string(), ResMessageBean.class);
                        ResultBean resultBean = JSONObject.parseObject(resMessageBean.getSvcContBean().getResult(), ResultBean.class);
                        Logger.json(JSONObject.toJSONString(resMessageBean.getTcpContBean()));
                        Logger.json(resultBean.getResultData());
                        if ("SUCCESS".equals(resultBean.getResultCode())) {
                            if (resultBean.getResultMsg() == null) {
                                return "";
                            } else {
                                return resultBean.getResultMsg();
                            }
                        } else {
                            throw new ServerException(resultBean.getResultCode(), resultBean.getResultMsg());
                        }
                    }
                });
            }
        };
    }

    public static ObservableTransformer<ResponseBody, String> rxTranslateUploadImage() {
        return new ObservableTransformer<ResponseBody, String>() {
            @Override
            public ObservableSource<String> apply(Observable<ResponseBody> upstream) {
                return upstream.map(new Function<ResponseBody, String>() {
                    @Override
                    public String apply(ResponseBody responseBody) throws Exception {
                        ResMessageBean resMessageBean = JSONObject.parseObject(responseBody.string(), ResMessageBean.class, Feature.InitStringFieldAsEmpty);
                        ResultBean resultBean = JSONObject.parseObject(resMessageBean.getSvcContBean().getResult(), ResultBean.class);
                        Logger.json(JSONObject.toJSONString(resMessageBean.getTcpContBean()));
                        Logger.json(resultBean.getResultData());
                        if ("SUCCESS".equals(resultBean.getResultCode())) {
                            return resultBean.getResultData();
                        } else {
                            throw new ServerException(resultBean.getResultCode(), resultBean.getResultMsg());
                        }
                    }
                });
            }
        };
    }

    public static <T> AutoDisposeConverter<T> bindLifecycleOwner(LifecycleOwner lifecycleOwner) {
        return AutoDispose.<T>autoDisposable(AndroidLifecycleScopeProvider.from(lifecycleOwner));
    }

    public static <T> ObservableTransformer<T, T> rxSchedulerHelper() {    //compose简化线程
        return new ObservableTransformer<T, T>() {
            @Override
            public ObservableSource<T> apply(Observable<T> observable) {
                return observable.subscribeOn(Schedulers.io())
                        .observeOn(AndroidSchedulers.mainThread());
            }
        };
    }


}
